import { defineStore } from 'pinia'
import request from '@/utils/request'

// 默认关键字的接口
export interface ReqDefaultKeyword {
  keyword: string
  schemeUrl: string
  highlight: number
  hidden: number
  type: number
  algSort: boolean
  extra: {
    resource: {
      materialName: string
      resourcesId: number
      materialId: number
    }
  }
}

// 热门关键字的接口
export interface ReqHotKeyword {
  keyword: string
  schemeUrl: null
  highlight: number
  hidden: number
  type: number
  algSort: boolean
  extra: {
    materialContentFrom: number
    rcmdSort: boolean
    taskType: number
    alg_personalized: string
    itemFrom: number
    resourcesId: number
  }
}

// 默认关键字和热门关键字的接口
export interface ReqKeyWord {
  defaultKeyword: ReqDefaultKeyword
  defaultKeywords: ReqDefaultKeyword[]
  hotKeywordVOList: ReqHotKeyword[]
  colorfulEggList: []
}

// 单个分类的接口
export interface ReqCategoryL1 {
  id: number
  name: string
  frontName: null
}

// 单个sku的接口
export interface ReqSku {
  id: number
  counterPrice: number
  retailPrice: number
  primarySku: boolean
  sellVolume: number
  noActivitySellVolume: number
  valid: boolean
  itemSkuSpecValueList: null
  preSellStatus: number
  preSellPrice: number
  preSellVolume: number
  preSellDesc: null
  purchaseAttribute: number
  giftCardFlag: false
  virtualFlag: false
  limitedFlag: number
  promId: number
  preLimitFlag: number
  limitPurchaseFlag: boolean
  limitPurchaseCount: number
  limitPointCount: number
  appExclusiveSkuInfo: null
  buttonType: number
  limitPrice: null
  selected: boolean
  promValid: boolean
  hdrkDetailVOList: null
  promotionDesc: null
  itemTagList: []
  points: number
  pointsPrice: number
  pic: null
  preemptionStatus: number
  noSaleDesc: null
  spmcBanner: null
  appFreshmanBannerVO: null
  confineType: number
  isSatisfy: boolean
  activityPrice: null
  cnt: number
  accessoryFlag: boolean
  depositSkuVO: null
  extraServiceFlag: number
  extraServiceItemVOs: null
  promBanner: null
  promoTip: null
  shoppingReward: null
  skuTitle: string
  presentUrl: null
  priceDesc: null
  buyTitle: null
  calcPrice: number
  desc: string
  skuLimit: null
  operationAttribute: number
  canReturnReward: boolean
  promoTips: null
  couponShortNameList: null
  itemDiscountDetail: null
  spmcFinalPriceBannerVO: null
  skuFreight: null
  proDiscount: null
  versionForbidDesc: null
  fullRefundPolicy: null
  price: null
  banner: null
  showPrice: boolean
  pointTag: null
  pointTagPrefix: null
}

// 单个logo数据的接口
export interface ReqPreLogo {
  logoUrl: string
  width: number
  height: number
  type: number
}

// 单个商品的接口
export interface ReqDirectly {
  id: number
  listPicUrl: string
  name: string
  seoTitle: string
  simpleDesc: string
  primaryPicUrl: string
  primarySkuId: number
  retailPrice: number
  counterPrice: number
  sortOriginPrice: number
  status: number
  rank: number
  soldOut: boolean
  underShelf: boolean
  updateTime: number
  itemDetail: null
  skuList: ReqSku[]
  attrList: null
  skuMap: null
  skuSpecList: null
  sellVolume: number
  reportPicList: null
  issueList: null
  unitPrice: null
  tagList: null
  hdrkDetailVOList: null
  comments: null
  newItemFlag: boolean
  primarySkuPreSellPrice: number
  primarySkuPreSellStatus: number
  pieceNum: number
  pieceUnitDesc: string
  colorNum: number
  limitedFlag: number
  promId: number
  preLimitFlag: number
  gradientPrice: null
  productPlace: string
  remark: null
  flashPageLink: string
  promotionDesc: string
  specialPromTag: string
  extraPrice: string
  appExclusiveFlag: boolean
  appExclusivePrice: null
  promTag: null
  tryOutEventReport: null
  layawayList: null
  itemTagList: []
  isPreemption: number
  preemptionStatus: number
  couponShortNameList: null
  buttonType: number
  sloganTip: null
  showTime: number
  onSaleTime: number
  characteristicList: null
  itemPromValid: boolean
  autoOnsaleTime: number
  autoOnsaleTimeLeft: number
  displaySkuId: number
  saleCenterDesc: null
  presentUrl: null
  saleCenterSkuId: number
  saleCenterSkuSpec: null
  topCommentVO: null
  itemType: number
  adBanners: null
  points: number
  showPoints: boolean
  pointsPrice: number
  valueReturnDesc: null
  forbidExclusiveCal: boolean
  commentCount: number
  commentWithPicCount: number
  freightInfo: null
  itemLimit: null
  itemSizeTableFlag: boolean
  itemSizeTableDetailFlag: boolean
  itemSizeTableList: null
  freeTryVO: null
  purchaseRate: null
  jumpUrl: null
  zcSearchFlag: boolean
  featuredSeries: null
  pointsStatus: number
  sortFlag: number
  spmcBanner: null
  appFreshmanBannerVO: null
  source: number
  categoryList: null
  depositDetailVO: null
  scenePicUrl: string
  couponPrice: null
  bonusBanner: null
  couponConflict: boolean
  extraServiceFlag: number
  forbiddenBuy: boolean
  forbidBuyDesc: null
  bigPromotion: null
  spmcOpenGiftItemDesc: null
  discountDesc: null
  subtractPriceDesc: null
  goodCmtRate: null
  showCommentEntrance: boolean
  relatedItemCommentTag: null
  rewardDesc: null
  categoryL2Id: number
  promLogo: null
  listPromBanner: null
  detailPromBanner: null
  promoTip: null
  rewardShareFlag: boolean
  shoppingReward: null
  shoppingRewardRule: null
  promDesc: null
  promoTips: null
  picMode: number
  extra: null
  recommendReason: null
  shieldSpecialChannel: boolean
  itemDiscountDetail: null
  spmcFinalPriceBannerVO: null
  buyTitle: null
  noticeText: null
  skuFreight: null
  proDiscount: null
  purchaseMethodVO: null
  fullRefundPolicy: null
  freeTryId: number
  zoomTransPicV2Url: string
  monthlySavingCard: null
  welfareCardVO: null
  brandInfo: null
  simpleBrandInfo: null
  countryInfo: null
  finalPriceInfoVO: {
    banner: {
      logo: null
      title: string
      price: null
      content: string
    }
    priceInfo: {
      finalPrice: {
        prefix: null
        price: string
        suffix: null
      }
      counterPrice: string
      basicPrice: null
    }
    type: 0
  }
  topLogo: {
    logoUrl: string
    width: number
    height: number
    type: number
  }
  preLogo: ReqPreLogo[]
  price: null
  banner: null
  showPrice: boolean
  pointTag: null
  pointTagExtra: null
  pointTagPrefix: null
  zc: boolean
  wapSchemeUrl: null
  auctionInfoVO: null
  spmcFinalPriceCalcResultBean: null
  listProPriceInfoDTO: null
}

// 搜索数据的接口
export interface ReqSearchData {
  categoryInfoList: []
  categoryL1List: ReqCategoryL1[]
  directActualQuery: []
  directOrginQuery: string
  directlyList: ReqDirectly[]
  fromSearch: number
  hasMore: boolean
  matchType: number
  searchEggActivityResultVO: null
  searchParams: {
    floorPrice: number
    stillSearch: boolean
    matchType: number
    source: number
    searchWordSource: number
    itemId: number
    searchId: string
    size: number
    sortType: number
    upperPrice: number
    descSorted: boolean
    keyword: string
    categoryId: number
  }
  searchVersion: string
  similarActualQuery: []
  similarCategoryInfoList: []
  similarList: []
  similarOrginQuery: string
  similarSearchVersion: string
  suggestTermList: []
  topics: []
}

// 搜索仓库stata数据的接口
interface ReqSearchStoreState {
  defaultKeyword: ReqDefaultKeyword
  hotKeywordVOList: ReqHotKeyword[]
  timeKeywordList: string[]
  categoryL1List: ReqCategoryL1[]
  directlyList: ReqDirectly[]
  historyList: string[]
}

export const useSearchStore = defineStore('search', {
  state(): ReqSearchStoreState {
    return {
      // 默认关键字
      defaultKeyword: {
        keyword: '',
        schemeUrl: '',
        highlight: 0,
        hidden: 0,
        type: 0,
        algSort: false,
        extra: {
          resource: {
            materialName: '',
            resourcesId: 0,
            materialId: 0
          }
        }
      },
      // 热门关键字列表
      hotKeywordVOList: [],
      // 实时关键字列表
      timeKeywordList: [],
      // 分类列表
      categoryL1List: [],
      // 商品列表
      directlyList: [],
      // 历史记录列表
      historyList: JSON.parse(localStorage.getItem('historyList_key') as string) || []
    }
  },
  actions: {
    // 获取默认关键字和热门关键字
    async getSearchInit() {
      try {
        const data = await request.get<any, ReqKeyWord>('/xhr/search/init.json')
        this.defaultKeyword = data.defaultKeyword
        this.hotKeywordVOList = data.hotKeywordVOList
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取实时关键字列表
    async getSearchAutoComplete(keyword: string) {
      const data = await request.post<any, string[]>(
        '/xhr/search/searchAutoComplete.json?csrf_token=31670f97c0035e50d0221a40f1f1d576',
        {
          keywordPrefix: keyword
        },
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }
      )
      this.timeKeywordList = data
    },
    // 获取搜索商品
    async getSearchGoods(keyword: string) {
      const data = await request.get<any, ReqSearchData>(
        `/xhr/search/search.json?csrf_token=31670f97c0035e50d0221a40f1f1d576&__timestamp=1680777235912&keyword=${keyword}&sortType=0&descSorted=false&categoryId=0&matchType=0&floorPrice=-1&upperPrice=-1&size=40&itemId=0&stillSearch=false&searchWordSource=1&needPopWindow=true&_stat_search=userhand`
      )
      this.categoryL1List = data.categoryL1List
      this.directlyList = data.directlyList
    },
    // 添加历史记录
    addHistory(keyword: string) {
      if (this.historyList.includes(keyword)) return
      this.historyList.push(keyword)
      localStorage.setItem('historyList_key', JSON.stringify(this.historyList))
    },
    // 删除历史记录
    deleteHistory() {
      this.historyList = []
      localStorage.setItem('historyList_key', JSON.stringify(this.historyList))
    }
  },
  getters: {}
})
